<?php


namespace app\api\controller;


use addons\alisms\Alisms;
use app\admin\controller\auth\Admin;
use app\admin\model\Student;
use app\api\ApiHandle;
use app\common\controller\Api;
use app\common\controller\Util;
use app\common\library\Sms;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;


class Bizteacher extends ApiHandle
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['register'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Student;
    }

    /**
     * Notes: 注册接口
     * User: zhao
     * Date: 2020/8/17
     * Time: 10:16
     */
    public function register()
    {
        $param = $this->request->post();
        // 数据校验START
        $data = $this->validate($param, [
            'phone' => 'require|regex:/^1[3456789]\d{9}$/',
            'password' => 'require|regex:/^[0-9a-z_.]{8,16}$/i',
        ], [
                'phone.require' => '手机号码必填',
                'phone.regex' => '手机号码格式错误',
                'password.require' => '密码为必填',
                'password.regex' => '密码格式为8-16位大小写字母、数字、特殊符号',
            ]
        );
        if (!empty($data) && $data !== true) {
            return $this->error($data);
        }
        // 验证验证码的正确
        $smsResult = Sms::check($param['phone'], $param['code'], 'register');
        $smsResult ?: $this->error("验证码错误");

        $phone = $param['phone'];
        $password = $param['password'];
        $code = $param['invite_code'];
        // 数据校验END
//        插入user表
//        思路：默认注册的教师不能登录，需要管理员审核之后才可以登录
        $ret = $this->auth->register($phone, $password, '', $phone, ['group_id' => 2]);
        if ($ret) {
//            res作为admin的id标识
//            插入admin表
            $ret = $this->auth->registerTeacher($phone, $password, '', $phone, []);
            Db::name("auth_group_access")->insert(['uid' => $ret, 'group_id' => 7]);
        }
        $icode = Util::getInviteCode();
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $params['invite_code'] = $icode;
            $params['user_id'] = $data['userinfo']['user_id'];
            $params['admin_id'] = $ret;
            $params['phone'] = $phone;
            $params['name'] = $phone;
            $params['nick_name'] = $phone;
            $params['register_time'] = date("Y-m-d H:i:s");
            $params['create_time'] = date("Y-m-d H:i:s");
//            插入teacher表
            $result = Db::name('teacher')->insert($params);
            $tid = Db::name('teacher')->getLastInsID();


            $hooks_data = [
                // 用户姓名
                'name' => '教师',
                // 用户所在表id
                'uid' => $tid,
                // 用户类型 student / teacher / help
                'type' => 'teacher',
            ];
            $data = Hook::listen("createAccountForUser", $hooks_data, '', true);

            if (!empty($code)) {
                $teacher_invest = [
                    'role' => 'teacher',
                    'uid' => $tid,
                    'invite_code' => $code,
                ];
                Hook::listen("createTeacherInvest", $teacher_invest, '', true);
            }

            if ($result) {
                $this->success(__('Sign up successful'), $data);
            } else {
                $this->error("系统繁忙");
            }
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * Notes:完善信息
     * User: zhao
     * Date: 2020/8/17
     * Time: 11:57
     */
    public function perfectTeacherInfo()
    {
        $param['nick_name'] = $this->request->request('nick_name');
        $param['header'] = $this->request->request('header');
        $param['sex'] = $this->request->request('sex');
        $param['age'] = $this->request->request('age');
        $param['english_name'] = $this->request->request('english_name');
        $param['birthday'] = $this->request->request('birthday');
        $param['address'] = $this->request->request('address');
        $param['grade'] = $this->request->request('grade');
        $param['school'] = $this->request->request('school');
        $user_id = $this->auth->id;
        // 启动事务
        $flag = true;
        Db::startTrans();
        try {
            Db::name("teacher")->where("user_id", $user_id)->update($param);

            $teacher = Db::name("teacher")->where("user_id", $user_id)->field('password', true)->find();
            $userData['id'] = $user_id;
            $userData['nickname'] = $param['nick_name'];
            $userData['avatar'] = $param['header'];
            Db::name('user')->update($userData);

            $adminData['id'] = $teacher['admin_id'];
            $adminData['nickname'] = $param['nick_name'];
            $adminData['avatar'] = $param['header'];
            Db::name('admin')->update($adminData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        if ($flag) {
            return $this->success("完善成功", $teacher);
        } else {
            return $this->error("系统繁忙");
        }
    }

    /**
     * 获取教师详情
     */
    public function teacherInfo()
    {

        $user_id = $this->auth->id;
//            $teacher = Db::name("teacher")->where("user_id",$user_id)->field('password',true)->fetchSql()->find();
        $teacher = Db::name("teacher")->where("user_id", $user_id)->field('password', true)->find();
        return $this->success("教师详情", $teacher);
    }

    /**
     *  addAuthResource
     * {"authJson":
     * [{"name":"教师资格证","resouce_img":"/uploads/20200814/bc7dafbf173d0b9648a8af2ffd547ba7.jpeg"},
     * {"name":"教师资格证2","resouce_img":"/uploads/20200814/bc7dafbf173d0b9648a8af2ffd547bab.jpeg"},
     * ]}
     */
    public function addAuthResource()
    {

        $user_id = $this->auth->id;

        $teacher = Db::name("teacher")->where("user_id", $user_id)->find();

        $userData['id'] = $teacher["id"];
        //$authJson = $this->request->request();
        $authJson = request()->put();//
//        print_r($authJson);
//        exit();
        //思路 将用户的认证资源循环批量插入
        $authJsonArray = $authJson['authJson'];
//        print_r($authJsonArray);
//        exit();
        foreach ($authJsonArray as $key => &$value) {
            $value['teacher_id'] = $userData['id'];
            /*$value['resouce_img'] = $value['img'];
            unset($value['img']);
            */
        }
        try {
//            dump($authJsonArray);
//            $sql=Db::name('teacher_auth')->fetchSql(true)->insertAll($authJsonArray);
//            print_r($sql);
//            die();
            Db::name('teacher_auth')->insertAll($authJsonArray);
        } catch (\Exception $e) {
            return $this->error("失败", $e->getMessage());
        }
        return $this->success("成功");

    }

    /**
     * auth zhao
     * Date 2020/8/24
     * Time 14:36
     *  重置密码
     */
    public function resetpassword()
    {
        $params = $this->request->post();
        $data = $this->validate($params, [
            'password' => 'require|regex:/^[0-9a-z_.]{8,16}$/i',
        ], [
                'password.require' => '密码为必填',
                'password.regex' => '密码格式为8-16位大小写字母、数字、特殊符号',
            ]
        );
        if (!empty($data) && $data !== true) {
            return $this->error($data);
        }
        try {
            $user_id = $this->auth->id;
            if ($user_id) {
                $teacher = Db::name('teacher')->where('user_id', $user_id)->find();
                if (!$teacher) {
                    throw new Exception('用户不存在');
                }
                $params['id'] = $teacher['admin_id'];
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
//                更新admin表和user表
                Db::name('admin')->update($params);
                $params['id'] = $teacher['user_id'];
                Db::name('user')->update($params);
            }
        } catch (\Exception $e) {
            return $this->error("失败", $e->getMessage());
        }
        return $this->success("成功");
    }

    // 获取教师站内信息未读总数
    public function getNoNotices()
    {
        $type = $this->request->get('type', 1);
        $teacherINFO = Util::getUserInfo($this->auth->id);
        if ($type == 1) {
            $count = Db::name('notices')->where(['to_id' => $teacherINFO['id'], 'to_role' => 'teacher', 'is_read' => 0])->count();
        } else {
            $count = Db::name('notices')->where(['to_id' => $teacherINFO['id'], 'to_role' => 'teacher'])->field('id,created_time,type,is_read,title,content')->order('created_time DESC')->select();
        }
        return $this->success('成功', $count);
    }

    /**
     * Notes:获取学生列表
     * User: XingLiangRen
     * Date: 2020/9/3
     * Time: 15:22
     */
    public function getStudentList()
    {
        $offset = $this->request->get('offset', 0);
        $limit = $this->request->get('limit', 10);
        $user_name = $this->request->get('user_name');
        $grade = $this->request->get('grade');
        $teacherINFO = Util::getUserInfo($this->auth->id);
        $where = ['c.teacher_id' => $teacherINFO['id']];
        if (Util::checkEmpty($user_name)) {
            $where['s.user_name'] = ['like', '%' . $user_name . '%'];
        }
        if (Util::checkEmpty($grade)) {
            $where['s.grade'] = ['=', $grade];
        }
        $res = Db::name('course')->alias('c')
            ->join('order o', 'c.id = o.courseId', 'LEFT')
            ->join('student s', 'o.userId = s.id')
            ->where($where)
            ->field('s.id,s.user_name,s.sex,s.school,s.grade,c.title,c.section_num,c.id as course_id')
            ->group('s.id')
            ->limit($offset, $limit)
            ->select();
        foreach ($res as &$v) {
            $count = Db::name('course_lesson_learn')->where(['user_id' => $v['id'], 'course_id' => $v['course_id']])->count();
            $v['plan'] = 0;
            if ($count !== 0) {
                $v['plan'] = $count / $v['section_num'];
            }
            $lesson_id = \db('course_lesson_learn')->where(['user_id' => $v['id'], 'course_id' => $v['course_id']])->max('lesson_id');
            $lesson_title = Db::name('course_lesson')->where('id', $lesson_id)->field('title')->find();
            $v['lesson_title'] = $lesson_title['title'] ?? "暂无学习课程";
        }
        $this->success('查询成功', $res);
    }
}